﻿package com.push.notifications;


import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;


import com.push.notifications.R;
import com.push.notifications.categoryItem;


import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;

import android.content.DialogInterface;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

public class DialogCategory extends Activity {

	 ListView listView;
	 UI_ListService_Mutil adapter;
	 static List<categoryItem> list = new ArrayList<categoryItem>();
	 static boolean Dialog_ok= false;
	 static boolean Dialog_cancel= false;
	 public static categoryItem itemParent;	 
	 public static boolean  bFinally = false;
	 private Handler _handle = null;
	 private int waited = 0;
	 public boolean hasNotDialog = true;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       
        
                     
        if(!CUtilsFunction.checkConnect(this))
		 {
        	setContentView(R.layout.service_mutil);
         	listView = (ListView) findViewById(R.id.list_webView1);
             TextView text1= (TextView) findViewById(R.id.ser_Message);
             text1.setText(itemParent.getName()); 
             final ImageButton buttonClose = (ImageButton) findViewById(R.id.ser_button13);
             buttonClose.setOnClickListener(new View.OnClickListener() {
                 public void onClick(View v) {
                 	//close Activitys
                     finish();
                 }
             });
             
        	list = databaseWrapper.getListCategoryById(this,itemParent.getCategory());
        	adapter = new UI_ListService_Mutil(this,list);
     	   listView.setAdapter(adapter); 
     	   
     	   adapter.notifyDataSetChanged();  
		 }
		 else //Online
		 {
			 _handle = new Handler(){
				 public void handleMessage(Message msg) {
		                super.handleMessage(msg);
		              switch(msg.what) {
		              case 0:
		            	  updateListView();
		            	  break;
		              case 1:
	                	showDialog(Definitions.DIALOG_WARNING);
	                	hasNotDialog= false;
	                	break;
		              }
		            }
			 };
			
			getJsonSubNews(itemParent.getCategory());
			Thread getSubNewsThread = new Thread() {
				
				@Override
				public void run() {
					try {
						
						while ((WebServicesTask.sData.equalsIgnoreCase(""))) {
							sleep(100);								
							if(hasNotDialog && WebServicesTask.bNotReponse == true)
							{		
								_handle.sendEmptyMessage(Definitions.DIALOG_WARNING);
								 
							}
						  
						}
					} catch (InterruptedException e) {
						// do nothing
					} finally {
						//end loading
						_handle.sendEmptyMessage(0);
											
					}
				}
			};
			getSubNewsThread.start();
		 }
    }
    
    public void updateListView()
    {
    	
    	 setContentView(R.layout.service_mutil);
     	listView = (ListView) findViewById(R.id.list_webView1);
         TextView text1= (TextView) findViewById(R.id.ser_Message);
         text1.setText(itemParent.getName()); 
         final ImageButton buttonClose = (ImageButton) findViewById(R.id.ser_button13);
         buttonClose.setOnClickListener(new View.OnClickListener() {
             public void onClick(View v) {
             	//close Activitys
                 finish();
             }
         });
         
    	list.clear();
    	
        list = getData();
        //Compare with in database
        for(int k =0 ; k < list.size(); k++)
		 {
        	categoryItem itemTemp = list.get(k);					 
			 categoryItem itemDb = databaseWrapper.getCategory(this,itemTemp.getCategory(),itemTemp.getParentId());
			 if(itemDb != null)
			 {
				 itemTemp.setSelected(itemDb.isSelected());
				 list.set(k, itemTemp);
			 }
		 }
 
	   adapter = new UI_ListService_Mutil(this,list);
	   listView.setAdapter(adapter); 
	   
	   adapter.notifyDataSetChanged(); 
	   
	   //Empty database    
         databaseWrapper.deleteAllCategoryHaveParentId(this,itemParent.getCategory());
		 for(int j =0 ; j < list.size(); j++)
		 {
			 categoryItem itemTemp = list.get(j);	
			 categoryItem itemDb = databaseWrapper.getCategory(this,itemTemp.getCategory(), itemTemp.getParentId());
			 if(itemDb == null)
				 databaseWrapper.insertCategory(this,itemTemp);			
		 }
		 Map<String, String> map;
    }
  
    
    public  void getJsonSubNews(int nParentId)
   	{    	
    	WebServicesTask.bNotReponse = false;
    	WebServicesTask.sData = "";
       	String urlRequest = Definitions.SUBNEWS_URL + nParentId; 
       	WebServicesTask wst = new WebServicesTask(WebServicesTask.GET_TASK, this, Definitions.SUB_LOADING);
       	wst.setLoading(true);
       	wst.execute(new String[] {urlRequest});
   	 }
      
    
	 public  List<categoryItem> getData()
	 {    		
		 List<categoryItem> listNew = new ArrayList<categoryItem>();
		 
		 try {
				JSONArray jsonArray = new JSONArray(WebServicesTask.sData);								
				for (int i = 0; i < jsonArray.length(); i++) {
					JSONObject jsonObject = jsonArray.getJSONObject(i);

					String sId = jsonObject.getString("extendId");
					int nId = Integer.parseInt(sId);
					String sParentId = jsonObject.getString("parentId");
					int nParentId = Integer.parseInt(sParentId);
					String sName = jsonObject.getString("extendName");
					String sIdIcon = jsonObject.getString("extendIcon");
					String sUrlImage = Definitions.LINK_TEST_DOWNLOAD + sIdIcon + "&w=45&h=45";
					String sCommand = jsonObject.getString("extendCommand");
					String sDate = jsonObject.getString("lastUpdate");
					String sDesc = jsonObject.getString("extendDesc");
					listNew.add(new categoryItem(sName,sUrlImage,true,nId,nParentId,i,sCommand,sDate,sDesc));
				}					
				
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		 	
		return listNew;
	 }
	 	   
  
		@Override
		protected Dialog onCreateDialog(int id) {
			Builder builder = new AlertDialog.Builder(this);
			AlertDialog dialog = null;
		    switch (id) {
		    
		    case Definitions.DIALOG_WARNING:
			     // Create out AlterDialog
			     
			     builder.setMessage(Definitions.WARNING_INTERNET);
			     builder.setCancelable(true);
			     builder.setPositiveButton((Definitions.TITLE_QUIT),
			    		    new DialogInterface.OnClickListener() {
			         public void onClick(DialogInterface dialog, int whichButton) {
			          finish();
			         }
			        });
			     builder.setNegativeButton(Definitions.TITLE_RETRY,
			    		    new DialogInterface.OnClickListener() {
			         public void onClick(DialogInterface dialog, int whichButton) {
			        	 waited = 0;
			          dialog.cancel();
			          getJsonSubNews(itemParent.getCategory());
			          hasNotDialog= true;
			         }
			        });
			     dialog = builder.create();
			     dialog.show();
			     break;
		    case Definitions.DIALOG_ALERT:
		      // Create out AlterDialog
		    	categoryItem currentMode = adapter.getJustClick();		 
	        	 builder.setMessage(Definitions.CHECK_WARNING);
			     builder.setCancelable(true);
			     builder.setPositiveButton(Definitions.TITLE_OK,null);				    
			     dialog = builder.create();
			     dialog.show();
		         adapter.updateStatus(currentMode);
		         break;
		    }
		    return super.onCreateDialog(id);
		  }

		
		public void addRemoveServices()
		{
			categoryItem currentMode = adapter.getJustClick();
			int nCategory = currentMode.getCategory();
	    	if(currentMode.isSelected())
	    	{
	    		removeService(NotificationActivity.regId,Integer.toString(nCategory));		    		
	    		currentMode.setSelected(false);
	    	}
	    	else
	    	{
	    		
	    		AddServices(NotificationActivity.regId,Integer.toString(nCategory));		    		
	    		currentMode.setSelected(true);
	    		
	    	}
	    	int nStatus = 0;
	    	if(currentMode.isSelected())
	    		nStatus = 1;
	    	//Check the exist in database
	    	int nCategoryId = currentMode.getCategory();
	    	int nParentId = currentMode.getParentId();
	    	String sName = currentMode.getName();
	    	String sDesc = currentMode.getDesc();
	    	String sLink_icon = currentMode.s_image;
	    	categoryItem item = databaseWrapper.getCategory(this,nCategoryId, nParentId);
	    	
	    	if(item == null)
	    	{
	    		categoryItem itemNew = new categoryItem(sName, sLink_icon, false, nCategoryId, nParentId, -1, "title", "", sDesc);	    		    
	    		databaseWrapper.insertCategory(this,itemNew);
	    	}
	    	
	    	databaseWrapper.updateCategory(this, currentMode.getCategory(), currentMode.getParentId(),nStatus);
	    	
	    	adapter.updateStatus(currentMode);
		}
		  
		  //Assign category for device
		  public  void AddServices(String sId, String sCategoryId)
		 {    	
	        String urlRequest = Definitions.ADD_SERVICE ; 
	    	WebServicesTask wst = new WebServicesTask(WebServicesTask.POST_TASK, this, Definitions.ADD_SERVICE_LOADING);
	        wst.setLoading(true);
	        wst.addNameValuePair("regId", sId);
	        wst.addNameValuePair("categoryId", sCategoryId);
	        wst.execute(new String[] {urlRequest});
		 }
		  
		//remove category for device
		  public  void removeService(String sId, String sCategoryId)
		 {    	
	        String urlRequest = Definitions.REMOVE_SERVICE +  "/" +sId + "/" +sCategoryId; 
	    	WebServicesTask wst = new WebServicesTask(WebServicesTask.DEL_TASK, this, Definitions.REMOVE_SERVICE_LOADING);	
	    	 wst.setLoading(true);
	        wst.execute(new String[] {urlRequest});
		 }
		  
	
			@Override
			protected void onStart() {
				Log.e("DialogCategory", "onStart: ------onStart------------ -");
				super.onStart();
			}
			@Override
			protected void onStop() {
				if(GCMIntentService.AppInterrupt)
				{
					finish();
					NotificationActivity.han_notification.sendEmptyMessage(0);
				}
				Log.e("DialogCategory", "onStop: ------onStop------------ "+GCMIntentService.AppInterrupt);
				super.onStop();
			}
			  @Override
		  	public void onWindowFocusChanged(boolean hasFocus) {
			  if (hasFocus)
			  {
				  GCMIntentService.AppInterrupt =false;
			  }
			// TODO Auto-generated method stub
			  Log.e("DialogCategory", ": ------onWindowFocusChanged------------ onWindowFocusChanged-"+ GCMIntentService.AppInterrupt);
			super.onWindowFocusChanged(hasFocus);
		  	}
			@Override
			protected void 	onUserLeaveHint(){
				GCMIntentService.AppInterrupt =true;
				Log.e("DialogCategory", "onUserLeaveHint: ------onUserLeaveHint------------ "+ GCMIntentService.AppInterrupt);
				super.onUserLeaveHint();
			}

}
